package com.nwork.qingmanhua.imagedown;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

/**
 * 图片下载管理类
 */
public class ImageDownloader {
    private static ImageDownloader instance = null;
    private IMemoryCache memoryCache = new SoftMemoryCache();
    private IMemoryCache diskCache = new DiskMemoryCache();

    private ImageDownloader() {
    }

    /**
     * 获得ImageDownloader的实例
     *
     * @return
     */
    public static ImageDownloader getInstance() {
        if (instance == null) {
            instance = new ImageDownloader();
        }
        return instance;
    }

    /**
     * 下载图片
     *
     * @param url                   下载图片的url
     * @param imageView
     * @param imageDownloadListener
     */
    public void download(String url, ImageView imageView, ImageDownloadListener imageDownloadListener) {
        this.download(url, null, -1, null);
    }

    /**
     * 下载一个图片 设置到指定的控件上
     *
     * @param url  下载图片的地址
     * @param view 想要填充到的控件
     */
    public void download(String url, View view) {
        this.download(url, view, -1, null);
    }

    /**
     * 下载一个图片 得到下载的状态(测试有问题)
     *
     * @param url
     * @param listener 图片下载的监听接口
     */
    public void download(String url, ImageDownloadListener listener) {
        this.download(url, null, -1, listener);
    }

    /**
     * @param url         图片的url
     * @param view        ImageView
     * @param placeholder 资源文件
     */
    public void download(String url, View view, int placeholder) {
        this.download(url, view, placeholder, null);
    }

    /**
     * @param url         下载图片的url
     * @param view        图片填充的控件
     * @param placeholder 为指定的View（ImageView） 填充指定的资源文件
     * @param listener    图片下载的监听接口
     */
    public void download(String url, View view, int placeholder,
                         ImageDownloadListener listener) {
        if (TextUtils.isEmpty(url)) {
            callback(listener, null, ImageDownloadListener.ImageState.ERROR);
            if (placeholder != -1) {
                if (view instanceof ImageView) {
                    ((ImageView) view).setScaleType(ImageView.ScaleType.CENTER);
                    ((ImageView) view).setImageResource(placeholder);
                }
            }
            return;
        }

        if (view != null) {
            view.setTag(url);
        }

        // 从缓存拿图片
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null) {
            callback(listener, bitmap, ImageDownloadListener.ImageState.SUCCESS);
            setBitmapForView(url, view, bitmap);
            return;
        }

        // 开启异步线程，拿图片
        callback(listener, bitmap, ImageDownloadListener.ImageState.Downloading);
        DownloadTask task = new DownloadTask(listener, view);
        if (Build.VERSION.SDK_INT < 11) {
            task.execute(url);
        } else {
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
        }
    }

    private void callback(ImageDownloadListener listener, Bitmap bitmap,
                          ImageDownloadListener.ImageState state) {
        if (listener == null) {
            return;
        }

        if (state == ImageDownloadListener.ImageState.Downloading) {
            listener.onDownloading();
        } else if (state == ImageDownloadListener.ImageState.SUCCESS && bitmap != null
                && !bitmap.isRecycled()) {
            listener.onSuccess(bitmap);
        } else {
            listener.onError();
        }
    }

    private void setBitmapForView(String url, View view, Bitmap bitmap) {
        if (view == null || bitmap == null || TextUtils.isEmpty(url)
                || view.getTag() == null
                || !TextUtils.equals(url, view.getTag().toString())) {
            return;
        }

        if (view instanceof ImageView) {
            ImageView imageView = (ImageView) view;
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setImageBitmap(bitmap);
        } else {
            view.setBackgroundDrawable(new BitmapDrawable(bitmap));
        }
    }

    private class DownloadTask extends AsyncTask<String, Void, Bitmap> {
        private ImageDownloadListener listener;
        private View view;
        private String url;

        public DownloadTask(ImageDownloadListener listener, View view) {
            this.listener = listener;
            this.view = view;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            if (params != null && params.length > 0
                    && params[0] instanceof String) {
                url = params[0];
            }
            return diskCache.get(url);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                memoryCache.put(url, bitmap);
                callback(listener, bitmap, ImageDownloadListener.ImageState.SUCCESS);
                setBitmapForView(url, view, bitmap);
            } else {
                callback(listener, null, ImageDownloadListener.ImageState.ERROR);
            }
        }
    }
}
